// https://leetcode.cn/problems/search-insert-position/description/

// 算法思路总结：
// 1. 二分查找定位目标值应插入的位置
// 2. 查找第一个大于等于目标值的元素位置
// 3. 使用左开右开区间维护查找边界
// 4. 循环结束时r即为目标插入位置
// 5. 时间复杂度：O(log n)，空间复杂度：O(1)

#include <iostream>
using namespace std;

#include <vector>
#include <algorithm>

class Solution 
{
public:
    int searchInsert(vector<int>& nums, int target) 
    {
        int n = nums.size();
        int l = -1, r = n;

        while (l + 1 != r)
        {
            int mid = (l + r) >> 1;
            if (nums[mid] < target)
            {
                l = mid;
            }
            else
            {
                r = mid;
            }
        }

        return r;
    }
};

int main()
{
    vector<int> nums1 = {1,3,5,6}, nums2 = {1,3,5,6};
    int target1 = 5, target2 = 2;

    Solution sol;

    cout << sol.searchInsert(nums1, target1) << endl;
    cout << sol.searchInsert(nums2, target2) << endl;

    return 0;
}